#!/usr/bin/env node

/**
 * Health Check Script
 *
 * standalone health check for production monitoring
 */

const http = require('http');

const options = {
    hostname: 'localhost',
    port: process.env.PORT || 3000,
    path: '/health',
    method: 'GET',
    timeout: 5000
};

const req = http.request(options, (res) => {
    let data = '';

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        try {
            const health = JSON.parse(data);

            if (res.statusCode === 200 && health.status === 'healthy') {
                console.log('✅ Service is healthy');
                console.log(`   Uptime: ${Math.round(health.uptime / 1000)}s`);
                console.log(`   Version: ${health.version}`);
                console.log(`   Checks: ${Object.keys(health.checks || {}).length} performed`);
                process.exit(0);
            } else {
                console.log('❌ Service is unhealthy');
                console.log(`   Status: ${health.status}`);
                console.log(`   Response: ${JSON.stringify(health, null, 2)}`);
                process.exit(1);
            }
        } catch (error) {
            console.log('❌ Invalid health check response');
            console.log(`   Error: ${error.message}`);
            console.log(`   Response: ${data}`);
            process.exit(1);
        }
    });
});

req.on('error', (error) => {
    console.log('❌ Health check failed');
    console.log(`   Error: ${error.message}`);
    process.exit(1);
});

req.on('timeout', () => {
    console.log('❌ Health check timeout');
    req.destroy();
    process.exit(1);
});

req.end();